<template>
  <div class="enterprise-center">
    <!-- 左侧导航栏 -->
    <EnterpriseSidebar />

    <!-- 右侧主内容区域 -->
    <main class="main-content">
      <!-- 页面标题和操作栏 -->
      <div class="page-header">
        <div class="header-left">
          <h1 class="page-title">{{ $t('enterpriseApplicationRecords.pageTitle') }}</h1>
          <div class="enterprise-info" v-if="enterpriseInfo">
            <el-tag type="info" size="small">
              {{ enterpriseInfo.enterpriseName }}
            </el-tag>
            <el-tag 
              :type="enterpriseInfo.certificationStatus === 'approved' ? 'success' : 'warning'" 
              size="small"
              style="margin-left: 8px;"
            >
              {{ getCertificationStatusText(enterpriseInfo.certificationStatus) }}
            </el-tag>
          </div>

        </div>
        <div class="header-right">
          <el-button type="primary" @click="goToCreateDemand">
            <el-icon><Plus /></el-icon>
            {{ $t('enterpriseApplicationRecords.publishNewDemand') }}
          </el-button>
        </div>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-select 
          v-model="filters.status" 
          :placeholder="$t('enterpriseApplicationRecords.selectStatus')" 
          style="width: 150px;"
          clearable
        >
          <el-option :label="$t('enterpriseApplicationRecords.all')" value="" />
          <el-option :label="$t('enterpriseApplicationRecords.submitted')" value="submitted" />
          <el-option :label="$t('enterpriseApplicationRecords.platformProcessing')" value="platform_processing" />
          <el-option :label="$t('enterpriseApplicationRecords.successfulMatch')" value="successful_match" />
          <el-option :label="$t('enterpriseApplicationRecords.failedMatch')" value="failed_match" />
        </el-select>
        
        <el-button type="primary" @click="loadApplications" style="margin-left: 10px;">{{ $t('enterpriseApplicationRecords.search') }}</el-button>
        <el-button @click="resetFilters" style="margin-left: 10px;">{{ $t('enterpriseApplicationRecords.reset') }}</el-button>
      </div>

      <!-- 申请记录列表 -->
      <div v-if="applications.length === 0 && !loading" class="empty-state">
        <el-empty 
          :description="$t('enterpriseApplicationRecords.noApplicationRecords')" 
          :image-size="120"
        />
      </div>

      <el-table v-else :data="applications" v-loading="loading" style="width: 100%">
        <el-table-column prop="requestId" :label="$t('enterpriseApplicationRecords.applicationId')" width="100" />
        <el-table-column prop="studentMaskedName" :label="$t('enterpriseApplicationRecords.studentName')" width="120" />
        <el-table-column prop="requestTime" :label="$t('enterpriseApplicationRecords.applicationTime')" width="160">
          <template #default="{ row }">
            {{ formatDate(row.requestTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="requestStatus" :label="$t('enterpriseApplicationRecords.applicationStatus')" width="120">
          <template #default="{ row }">
            <el-tag :type="getApplicationStatusType(row.requestStatus)">
              {{ row.statusDisplay }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="statusDescription" :label="$t('enterpriseApplicationRecords.statusDescription')" min-width="200" />
        <el-table-column :label="$t('enterpriseApplicationRecords.operation')" width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              @click="viewApplicationDetail(row.requestId)"
              v-if="row.requestStatus === 'successful_match'"
            >
              {{ $t('enterpriseApplicationRecords.viewDetails') }}
            </el-button>
            <el-button 
              size="small" 
              type="info" 
              @click="viewApplicationDetail(row.requestId)"
              v-else
            >
              {{ $t('enterpriseApplicationRecords.viewDetails') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 统计信息 -->
      <div class="summary-section" v-if="summary">
        <el-card>
          <template #header>
            <span>{{ $t('enterpriseApplicationRecords.statistics') }}</span>
          </template>
          <div class="summary-content">
            <div class="summary-item">
              <span class="label">{{ $t('enterpriseApplicationRecords.totalApplications') }}：</span>
              <span class="value">{{ summary.totalRequests }}</span>
            </div>
            <div class="summary-item">
              <span class="label">{{ $t('enterpriseApplicationRecords.currentFilter') }}：</span>
              <span class="value">{{ summary.currentFilter }}</span>
            </div>
            <div class="summary-item" v-if="enterpriseInfo">
              <span class="label">{{ $t('enterpriseApplicationRecords.enterpriseName') }}：</span>
              <span class="value">{{ enterpriseInfo.enterpriseName }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { 
  ArrowUp, ArrowDown, House, Document, List, Message, Setting, Plus, InfoFilled 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { applicationApi } from '../../api/index'
import EnterpriseSidebar from '@/components/EnterpriseSidebar.vue'
import { useI18n } from 'vue-i18n'

const { t, locale } = useI18n()

// 语言检测逻辑
const detectLanguage = () => {
  const savedLang = localStorage.getItem('lang')
  if (savedLang && (savedLang === 'zh' || savedLang === 'en')) {
    locale.value = savedLang
  } else {
    // 如果没有保存的语言设置，默认使用中文
    locale.value = 'zh'
    localStorage.setItem('lang', 'zh')
  }
}

const router = useRouter()

// 响应式数据
const loading = ref(false)
const applications = ref([])

const filters = reactive({
  status: '' // 申请状态筛选
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0,
  totalPages: 0,
  hasNext: false,
  hasPrev: false
})

const summary = ref(null)
const enterpriseInfo = ref(null)

// 加载申请记录列表
const loadApplications = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize
    }
    
    // 只有当状态筛选不为空时才添加status参数
    if (filters.status) {
      params.status = filters.status
    }
    
    // 调用申请记录API接口
    const response = await applicationApi.getMyRequests(params)
    
    if (response.code === 200) {
      applications.value = response.data.requests || []
      pagination.totalCount = response.data.pagination.totalCount
      pagination.totalPages = response.data.pagination.totalPages
      pagination.hasNext = response.data.pagination.hasNext
      pagination.hasPrev = response.data.pagination.hasPrev
      enterpriseInfo.value = response.data.enterpriseInfo
      
      // 构建统计信息
      summary.value = {
        totalRequests: response.data.pagination.totalCount,
        currentFilter: filters.status ? getApplicationStatusText(filters.status) : '全部',
        requestedBy: `enterprise:${enterpriseInfo.value?.enterpriseId || 'unknown'}`
      }
    } else {
      ElMessage.error(response.message || t('enterpriseApplicationRecords.loadFailed'))
    }
  } catch (error) {
    // 处理500错误 - 后端API可能未实现
    if (error.response?.status === 500) {
      // 不显示错误消息，直接显示空状态
      applications.value = []
      pagination.totalCount = 0
      pagination.totalPages = 0
      pagination.hasNext = false
      pagination.hasPrev = false
      
      // 设置临时的企业信息
      enterpriseInfo.value = {
        enterpriseId: 'unknown',
        enterpriseName: t('enterpriseApplicationRecords.enterpriseInfo'),
        certificationStatus: 'approved'
      }
      
      summary.value = {
        totalRequests: 0,
        currentFilter: t('enterpriseApplicationRecords.apiNotImplemented'),
        requestedBy: 'enterprise:unknown'
      }
      
      return
    }
    
    // 处理其他错误
    if (error.response?.status === 400) {
      ElMessage.error(t('enterpriseApplicationRecords.parameterError'))
    } else if (error.response?.status === 403) {
      ElMessage.error(t('enterpriseApplicationRecords.accessDenied'))
    } else if (error.response?.status === 404) {
      ElMessage.error(t('enterpriseApplicationRecords.enterpriseInfoNotFound'))
    } else {
      ElMessage.error(t('enterpriseApplicationRecords.networkError'))
    }
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadApplications()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadApplications()
}

const resetFilters = () => {
  filters.status = '' // 重置状态筛选
  pagination.currentPage = 1
  loadApplications()
}

// 查看申请详情
const viewApplicationDetail = (requestId) => {
  router.push({ name: 'enterprise-application-detail', params: { requestId: requestId } })
}

// 获取申请状态文本
const getApplicationStatusText = (status) => {
  const map = {
    'submitted': t('enterpriseApplicationRecords.submitted'),
    'platform_processing': t('enterpriseApplicationRecords.platformProcessing'),
    'successful_match': t('enterpriseApplicationRecords.successfulMatch'),
    'failed_match': t('enterpriseApplicationRecords.failedMatch')
  }
  return map[status] || status
}

// 获取申请状态类型
const getApplicationStatusType = (status) => {
  const map = {
    'submitted': 'info',
    'platform_processing': 'warning',
    'successful_match': 'success',
    'failed_match': 'danger'
  }
  return map[status] || 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getCertificationStatusText = (status) => {
  const map = {
    'unsubmitted': t('enterpriseApplicationRecords.unsubmitted'),
    'pendingreview': t('enterpriseApplicationRecords.pendingReview'),
    'rejected': t('enterpriseApplicationRecords.rejected'),
    'approved': t('enterpriseApplicationRecords.approved')
  }
  return map[status] || status
}

// 组件挂载
onMounted(() => {
  // 检测并设置语言
  detectLanguage()
  
  setTimeout(() => {
    loadApplications()
  }, 100)
})
</script>

<style scoped>
.enterprise-center {
  display: flex;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 左侧导航栏 */
.sidebar {
  width: 280px;
  background-color: #f8f9fa;
  border-right: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
}

.company-info {
  padding: 20px;
  border-bottom: 1px solid #e9ecef;
}

.company-logo {
  margin-bottom: 15px;
}

.logo-square {
  width: 40px;
  height: 40px;
  background-color: #1976d2;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 18px;
  border-radius: 4px;
}

.company-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.company-id {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.id-controls {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.navigation-menu {
  flex: 1;
  padding: 20px 0;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  color: #666;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
}

.nav-item:hover {
  background-color: #e9ecef;
  color: #333;
}

.nav-item.active {
  background-color: #e3f2fd;
  color: #1976d2;
  border-left-color: #1976d2;
  font-weight: 500;
}

.nav-item span {
  flex: 1;
}

/* 右侧主内容区域 */
.main-content {
  flex: 1;
  padding: 30px;
  background-color: white;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px 0;
}

.enterprise-info {
  display: flex;
  align-items: center;
  margin-top: 8px;
}



.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  background-color: #fafafa;
  border-radius: 8px;
  margin: 20px 0;
}

.empty-description {
  text-align: center;
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.summary-section {
  margin-top: 20px;
}

.summary-content {
  display: flex;
  gap: 20px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-item .label {
  font-weight: bold;
  margin-right: 8px;
  color: #666;
}

.summary-item .value {
  color: #409eff;
  font-weight: bold;
}

.application-count {
  font-weight: bold;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .enterprise-center {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e9ecef;
  }
  
  .main-content {
    padding: 20px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}
</style> 